package com.example.testplatform.service.impl;

import com.example.testplatform.common.LogUtils;
import com.example.testplatform.entity.Product;
import com.example.testplatform.mapper.ProductMapper;
import com.example.testplatform.service.ProductService;
import org.slf4j.Logger;
// 移除未使用的导入语句
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {
    
    private static final Logger logger = LogUtils.getLogger(ProductServiceImpl.class);
    
    @Autowired
    private ProductMapper productMapper;
    
    @Override
    public Map<String, Object> getProductList(Integer page, Integer pageSize, String search) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "PRODUCT_LIST_QUERY_START", "system", "开始分页查询产品列表");
        
        // 保存原始参数值用于日志记录
        final Integer originalPage = page;
        final Integer originalPageSize = pageSize;
        final String originalSearch = search;
        
        // 参数验证和final变量定义
        if (page == null || page <= 0) {
            page = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 10;
        }
        
        // 创建final变量供lambda表达式使用，定义在try-catch块之外
        final Integer finalPage = page;
        final Integer finalPageSize = pageSize;
        final String finalSearch = search;
        
        try {
            LogUtils.debug(logger, () -> "【产品管理】获取产品列表请求开始，页码: " + originalPage + ", 每页大小: " + originalPageSize + ", 搜索关键词: " + (originalSearch != null ? originalSearch : "空"));
            
            // 参数验证警告日志
            if (originalPage == null || originalPage <= 0) {
                LogUtils.warn(logger, "页码参数无效，自动设置为默认值: {}", finalPage);
            }
            if (originalPageSize == null || originalPageSize <= 0) {
                LogUtils.warn(logger, "每页大小参数无效，自动设置为默认值: {}", finalPageSize);
            }
            
            LogUtils.debug(logger, () -> "【产品管理】参数验证完成，处理后页码: " + finalPage + ", 处理后每页大小: " + finalPageSize);
            
            // 计算偏移量
            int offset = (finalPage - 1) * finalPageSize;
            LogUtils.debug(logger, () -> "【产品管理】计算查询偏移量: " + offset);
            
            // 执行查询
            LogUtils.info(logger, () -> "【产品管理】准备执行数据库查询，偏移量: " + offset + ", 每页大小: " + finalPageSize + ", 搜索词: " + (finalSearch != null ? finalSearch : "无"));
            List<Product> products = productMapper.findAll(offset, pageSize, search);
            LogUtils.debug(logger, () -> "【产品管理】查询产品列表完成，当前页获取产品数量: " + (products != null ? products.size() : 0));
            
            // 查询总数
            LogUtils.info(logger, () -> "【产品管理】准备查询产品总数量，搜索词: " + (finalSearch != null ? finalSearch : "无"));
            Integer total = productMapper.count(search);
            LogUtils.debug(logger, () -> "【产品管理】查询产品总数量完成，总记录数: " + (total != null ? total : 0));
            
            // 构建结果
            LogUtils.debug(logger, () -> "【产品管理】开始构建返回结果对象");
            Map<String, Object> result = new HashMap<>();
            result.put("list", products);
            result.put("total", total);
            
            LogUtils.info(logger, () -> "【产品管理】获取产品列表成功，共 " + total + " 条记录，当前页: " + (products != null ? products.size() : 0) + " 条，页码: " + finalPage);
            LogUtils.logPerformance(logger, "getProductList", startTime, System.currentTimeMillis());
            LogUtils.logBusiness(logger, "PRODUCT_LIST_QUERY_SUCCESS", "system", "产品列表分页查询成功，总记录数: " + total + ", 当前页: " + (products != null ? products.size() : 0));
            return result;
        } catch (Exception e) {
            LogUtils.error(logger, "【产品管理】获取产品列表异常: 页码=" + finalPage + ", 每页大小=" + finalPageSize + ", 搜索词=" + (finalSearch != null ? finalSearch : "空") + ", 错误: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "PRODUCT_LIST_QUERY_FAIL", "system", "产品列表分页查询失败: " + e.getMessage());
            throw e;
        }
    }
    
    @Override
    public List<Product> getAllProducts() {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "ALL_PRODUCTS_QUERY_START", "system", "开始获取所有产品");
        try {
            LogUtils.debug(logger, () -> "【产品管理】获取所有产品请求开始");
            
            LogUtils.info(logger, () -> "【产品管理】准备执行查询所有产品操作");
            List<Product> products = productMapper.findAll(null, null, null);
            LogUtils.debug(logger, () -> "【产品管理】查询所有产品完成，返回产品数量: " + (products != null ? products.size() : 0));
            
            // 记录返回的产品简要信息
            if (products != null && !products.isEmpty()) {
                StringBuilder productNames = new StringBuilder();
                for (int i = 0; i < Math.min(5, products.size()); i++) {
                    if (i > 0) productNames.append(", ");
                    productNames.append(products.get(i).getProductName()).append("(ID:").append(products.get(i).getId()).append(")");
                }
                if (products.size() > 5) {
                    productNames.append(" 等 ").append(products.size()).append(" 个产品");
                }
                LogUtils.debug(logger, () -> "【产品管理】返回的产品列表: " + productNames.toString());
            }
            
            LogUtils.info(logger, () -> "【产品管理】获取所有产品成功，共 " + (products != null ? products.size() : 0) + " 条记录");
            LogUtils.logPerformance(logger, "getAllProducts", startTime, System.currentTimeMillis());
            LogUtils.logBusiness(logger, "ALL_PRODUCTS_QUERY_SUCCESS", "system", "获取所有产品成功，记录数: " + (products != null ? products.size() : 0));
            return products;
        } catch (Exception e) {
            LogUtils.error(logger, "【产品管理】获取所有产品异常: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "ALL_PRODUCTS_QUERY_FAIL", "system", "获取所有产品失败: " + e.getMessage());
            throw e;
        }
    }
    
    @Override
    public Product getProductById(Long id) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "PRODUCT_DETAIL_QUERY_START", "system", "开始根据ID查询产品详情: " + id);
        try {
            // 参数验证
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "【产品管理】产品ID参数无效: {}", id);
                return null;
            }
            
            LogUtils.debug(logger, () -> "【产品管理】根据ID查询产品详情请求开始，产品ID: " + id);
            
            LogUtils.info(logger, () -> "【产品管理】准备执行查询产品详情操作，ID: " + id);
            Product product = productMapper.findById(id);
            
            if (product == null) {
                LogUtils.warn(logger, "【产品管理】未找到ID为 {} 的产品", id);
                LogUtils.logBusiness(logger, "PRODUCT_DETAIL_QUERY_NOT_FOUND", "system", "未找到产品: ID=" + id);
            } else {
                LogUtils.info(logger, () -> "【产品管理】找到产品: " + product.getProductName() + " (ID: " + product.getId() + "), 状态: " + product.getStatus());
                LogUtils.debug(logger, () -> "【产品管理】产品详情: ID=" + product.getId() + ", 名称=" + product.getProductName() + ", 描述=" + product.getDescription() + ", 产品负责人ID=" + product.getProductManagerId() + ", 测试负责人ID=" + product.getTestManagerId() + ", 状态=" + product.getStatus());
            }
            
            LogUtils.logPerformance(logger, "getProductById", startTime, System.currentTimeMillis());
            LogUtils.logBusiness(logger, "PRODUCT_DETAIL_QUERY_COMPLETE", "system", "产品详情查询完成，ID: " + id + ", 结果: " + (product != null ? "找到产品" : "未找到产品"));
            return product;
        } catch (Exception e) {
            LogUtils.error(logger, "【产品管理】根据ID查询产品异常: " + id + ", 错误: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "PRODUCT_DETAIL_QUERY_FAIL", "system", "产品详情查询失败: ID=" + id + ", 错误=" + e.getMessage());
            throw e;
        }
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean createProduct(Product product) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "PRODUCT_CREATE_START", "system", "开始创建产品");
        try {
            // 参数验证
            if (product == null) {
                LogUtils.warn(logger, "【产品管理】创建产品失败: 产品对象为空");
                LogUtils.logBusiness(logger, "PRODUCT_CREATE_FAIL", "system", "创建产品失败: 产品对象为空");
                return false;
            }
            
            if (product.getProductName() == null || product.getProductName().trim().isEmpty()) {
                LogUtils.warn(logger, "【产品管理】创建产品失败: 产品名称不能为空");
                LogUtils.logBusiness(logger, "PRODUCT_CREATE_FAIL", "system", "创建产品失败: 产品名称为空");
                return false;
            }
            
            LogUtils.debug(logger, () -> "【产品管理】创建产品请求开始，产品名称: " + product.getProductName());
            LogUtils.info(logger, () -> "【产品管理】准备创建新产品: " + product.getProductName());
            
            // 默认状态为启用
            if (product.getStatus() == null) {
                product.setStatus(1);
                LogUtils.debug(logger, () -> "【产品管理】产品状态为空，设置为默认值: 1(启用)");
            }
            
            // 记录创建前的完整产品信息
            LogUtils.debug(logger, () -> "【产品管理】待创建产品完整信息: " +
                    "名称=" + product.getProductName() + ", " +
                    "描述=" + (product.getDescription() != null ? product.getDescription() : "空") + ", " +
                    "产品负责人ID=" + (product.getProductManagerId() != null ? product.getProductManagerId() : "空") + ", " +
                    "测试负责人ID=" + (product.getTestManagerId() != null ? product.getTestManagerId() : "空") + ", " +
                    "状态=" + product.getStatus());
            
            LogUtils.info(logger, () -> "【产品管理】开始执行数据库插入操作");
            boolean result = productMapper.insert(product) > 0;
            
            if (result) {
                LogUtils.info(logger, () -> "【产品管理】产品创建成功: " + product.getProductName() + " (ID: " + product.getId() + ")");
                LogUtils.debug(logger, () -> "【产品管理】新产品ID分配: " + product.getId());
                LogUtils.logBusiness(logger, "PRODUCT_CREATE_SUCCESS", "system", "产品创建成功: " + product.getProductName() + " (ID: " + product.getId() + ")");
            } else {
                LogUtils.warn(logger, "【产品管理】产品创建失败: {}", product.getProductName());
                LogUtils.logBusiness(logger, "PRODUCT_CREATE_FAIL", "system", "产品创建失败: " + product.getProductName());
            }
            
            LogUtils.logPerformance(logger, "createProduct", startTime, System.currentTimeMillis());
            return result;
        } catch (Exception e) {
            LogUtils.error(logger, "【产品管理】创建产品异常: " + (product != null ? product.getProductName() : "空产品对象") + ", 错误: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "PRODUCT_CREATE_EXCEPTION", "system", "创建产品异常: " + e.getMessage());
            throw e;
        }
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateProduct(Product product) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "PRODUCT_UPDATE_START", "system", "开始更新产品");
        try {
            // 参数验证
            if (product == null) {
                LogUtils.warn(logger, "【产品管理】更新产品失败: 产品对象为空");
                LogUtils.logBusiness(logger, "PRODUCT_UPDATE_FAIL", "system", "更新产品失败: 产品对象为空");
                return false;
            }
            
            if (product.getId() == null || product.getId() <= 0) {
                LogUtils.warn(logger, "【产品管理】更新产品失败: 产品ID不能为空或无效");
                LogUtils.logBusiness(logger, "PRODUCT_UPDATE_FAIL", "system", "更新产品失败: 产品ID无效");
                return false;
            }
            
            LogUtils.debug(logger, () -> "【产品管理】更新产品请求开始，产品ID: " + product.getId() + ", 产品名称: " + (product.getProductName() != null ? product.getProductName() : "空"));
            
            // 检查产品是否存在
            LogUtils.info(logger, () -> "【产品管理】准备检查产品是否存在，ID: " + product.getId());
            Product existingProduct = productMapper.findById(product.getId());
            if (existingProduct == null) {
                LogUtils.warn(logger, "【产品管理】更新产品失败: 未找到ID为 {} 的产品", product.getId());
                LogUtils.logBusiness(logger, "PRODUCT_UPDATE_FAIL", "system", "更新产品失败: 产品不存在，ID=" + product.getId());
                return false;
            }
            
            LogUtils.info(logger, () -> "【产品管理】找到待更新产品: " + existingProduct.getProductName() + " (ID: " + existingProduct.getId() + ")");
            
            // 记录更新前后的信息对比
            StringBuilder updateLog = new StringBuilder();
            updateLog.append("【产品管理】产品更新信息对比 - 产品ID: " + product.getId() + ", ");
            if (!equals(existingProduct.getProductName(), product.getProductName())) {
                updateLog.append("名称从'" + existingProduct.getProductName() + "'变更为'" + product.getProductName() + "', ");
            }

            if (!equals(existingProduct.getDescription(), product.getDescription())) {
                updateLog.append("描述已变更, ");
            }
            if (!equals(existingProduct.getProductManagerId(), product.getProductManagerId())) {
                updateLog.append("产品负责人ID从'" + existingProduct.getProductManagerId() + "'变更为'" + product.getProductManagerId() + "', ");
            }
            if (!equals(existingProduct.getStatus(), product.getStatus())) {
                updateLog.append("状态从'" + existingProduct.getStatus() + "'变更为'" + product.getStatus() + "', ");
            }
            
            if (updateLog.length() > 0) {
                LogUtils.debug(logger, () -> updateLog.toString());
            } else {
                LogUtils.debug(logger, () -> "【产品管理】更新产品: 未检测到任何字段变更");
            }
            
            LogUtils.info(logger, () -> "【产品管理】开始执行数据库更新操作，ID: " + product.getId());
            boolean result = productMapper.update(product) > 0;
            
            if (result) {
                LogUtils.info(logger, () -> "【产品管理】产品更新成功: " + product.getId() + " - " + (product.getProductName() != null ? product.getProductName() : "空"));
                LogUtils.logBusiness(logger, "PRODUCT_UPDATE_SUCCESS", "system", "产品更新成功: ID=" + product.getId() + ", 名称=" + (product.getProductName() != null ? product.getProductName() : "空"));
            } else {
                LogUtils.warn(logger, "【产品管理】产品更新失败: {} - {}", product.getId(), (product.getProductName() != null ? product.getProductName() : "空"));
                LogUtils.logBusiness(logger, "PRODUCT_UPDATE_FAIL", "system", "产品更新失败: ID=" + product.getId());
            }
            
            LogUtils.logPerformance(logger, "updateProduct", startTime, System.currentTimeMillis());
            return result;
        } catch (Exception e) {
            LogUtils.error(logger, "【产品管理】更新产品异常: " + (product != null ? (product.getId() + " - " + product.getProductName()) : "空产品对象") + ", 错误: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "PRODUCT_UPDATE_EXCEPTION", "system", "更新产品异常: " + e.getMessage());
            throw e;
        }
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteProduct(Long id) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "PRODUCT_DELETE_START", "system", "开始删除产品");
        try {
            // 参数验证
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "【产品管理】删除产品失败: 产品ID不能为空或无效");
                LogUtils.logBusiness(logger, "PRODUCT_DELETE_FAIL", "system", "删除产品失败: 产品ID无效");
                return false;
            }
            
            LogUtils.debug(logger, () -> "【产品管理】删除产品请求开始，产品ID: " + id);
            
            // 检查产品是否存在
            LogUtils.info(logger, () -> "【产品管理】准备检查产品是否存在，ID: " + id);
            Product existingProduct = productMapper.findById(id);
            if (existingProduct == null) {
                LogUtils.warn(logger, "【产品管理】删除产品失败: 未找到ID为 {} 的产品", id);
                LogUtils.logBusiness(logger, "PRODUCT_DELETE_FAIL", "system", "删除产品失败: 产品不存在，ID=" + id);
                return false;
            }
            
            // 记录将要删除的产品信息
            LogUtils.info(logger, () -> "【产品管理】找到待删除产品: " + existingProduct.getProductName() + " (ID: " + existingProduct.getId() + "), 状态: " + existingProduct.getStatus());
            LogUtils.debug(logger, () -> "【产品管理】待删除产品详细信息: " +
                    "ID=" + existingProduct.getId() + ", " +
                    "名称=" + existingProduct.getProductName() + ", " +
                    "描述=" + (existingProduct.getDescription() != null ? existingProduct.getDescription() : "空") + ", " +
                    "产品负责人ID=" + (existingProduct.getProductManagerId() != null ? existingProduct.getProductManagerId() : "空") + ", " +
                    "测试负责人ID=" + (existingProduct.getTestManagerId() != null ? existingProduct.getTestManagerId() : "空") + ", " +
                    "状态=" + existingProduct.getStatus());
            
            // 检查是否有相关的测试申请单（假设有一个方法可以检查）
            // boolean hasRelatedApplications = checkRelatedApplications(id);
            // if (hasRelatedApplications) {
            //     LogUtils.warn(logger, "【产品管理】删除产品失败: 产品ID={} 存在相关的测试申请单，不允许删除", id);
            //     LogUtils.logBusiness(logger, "PRODUCT_DELETE_FAIL", "system", "删除产品失败: 产品存在相关依赖");
            //     return false;
            // }
            
            LogUtils.info(logger, () -> "【产品管理】开始执行数据库删除操作，ID: " + id);
            boolean result = productMapper.delete(id) > 0;
            
            if (result) {
                LogUtils.info(logger, () -> "【产品管理】产品删除成功: " + id + " - " + existingProduct.getProductName());
                LogUtils.logBusiness(logger, "PRODUCT_DELETE_SUCCESS", "system", "产品删除成功: ID=" + id + ", 名称=" + existingProduct.getProductName());
            } else {
                LogUtils.warn(logger, "【产品管理】产品删除失败: ID={}, 原因: 产品不存在或已被删除", id);
                LogUtils.logBusiness(logger, "PRODUCT_DELETE_FAIL", "system", "产品删除失败: ID=" + id);
            }
            
            LogUtils.logPerformance(logger, "deleteProduct", startTime, System.currentTimeMillis());
            return result;
        } catch (Exception e) {
            LogUtils.error(logger, "【产品管理】删除产品异常: " + id + ", 错误: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "PRODUCT_DELETE_EXCEPTION", "system", "删除产品异常: " + e.getMessage());
            throw e;
        }
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateProductStatus(Long id, Integer status) {
        long startTime = System.currentTimeMillis();
        LogUtils.logBusiness(logger, "PRODUCT_STATUS_UPDATE_START", "system", "开始更新产品状态");
        try {
            // 参数验证
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "【产品管理】更新产品状态失败: 产品ID不能为空或无效");
                LogUtils.logBusiness(logger, "PRODUCT_STATUS_UPDATE_FAIL", "system", "更新产品状态失败: 产品ID无效");
                return false;
            }
            
            if (status == null || (status != 0 && status != 1)) {
                LogUtils.warn(logger, "【产品管理】更新产品状态失败: 状态值无效，必须是0(禁用)或1(启用)");
                LogUtils.logBusiness(logger, "PRODUCT_STATUS_UPDATE_FAIL", "system", "更新产品状态失败: 状态值无效");
                return false;
            }
            
            LogUtils.debug(logger, () -> "【产品管理】更新产品状态请求开始，产品ID: " + id + ", 目标状态: " + status);
            
            // 检查产品是否存在
            LogUtils.info(logger, () -> "【产品管理】准备检查产品是否存在，ID: " + id);
            Product existingProduct = productMapper.findById(id);
            if (existingProduct == null) {
                LogUtils.warn(logger, "【产品管理】更新产品状态失败: 未找到ID为 {} 的产品", id);
                LogUtils.logBusiness(logger, "PRODUCT_STATUS_UPDATE_FAIL", "system", "更新产品状态失败: 产品不存在，ID=" + id);
                return false;
            }
            
            // 检查状态是否已经是目标状态
            if (existingProduct.getStatus().equals(status)) {
                LogUtils.info(logger, () -> "【产品管理】产品状态无需更新: ID=" + id + ", 状态已经是 " + status);
                LogUtils.logBusiness(logger, "PRODUCT_STATUS_UPDATE_NO_CHANGE", "system", "产品状态无需更新: ID=" + id + ", 状态=" + status);
                return true; // 虽然没有变更，但返回成功表示操作有效
            }
            
            LogUtils.info(logger, () -> "【产品管理】找到待更新状态的产品: " + existingProduct.getProductName() + " (ID: " + existingProduct.getId() + "), 当前状态: " + existingProduct.getStatus() + ", 目标状态: " + status);
            
            LogUtils.info(logger, () -> "【产品管理】开始执行数据库状态更新操作，ID: " + id + ", 新状态: " + status);
            boolean result = productMapper.updateStatus(id, status) > 0;
            
            if (result) {
                LogUtils.info(logger, () -> "【产品管理】产品状态更新成功: " + id + " - " + existingProduct.getProductName() + ", 从状态 " + existingProduct.getStatus() + " 变更为 " + status);
                LogUtils.logBusiness(logger, "PRODUCT_STATUS_UPDATE_SUCCESS", "system", "产品状态更新成功: ID=" + id + ", 名称=" + existingProduct.getProductName() + ", 状态从 " + existingProduct.getStatus() + " 变更为 " + status);
            } else {
                LogUtils.warn(logger, "【产品管理】产品状态更新失败: ID={}, 状态={}, 原因: 产品不存在或更新失败", id, status);
                LogUtils.logBusiness(logger, "PRODUCT_STATUS_UPDATE_FAIL", "system", "产品状态更新失败: ID=" + id + ", 目标状态=" + status);
            }
            
            LogUtils.logPerformance(logger, "updateProductStatus", startTime, System.currentTimeMillis());
            return result;
        } catch (Exception e) {
            LogUtils.error(logger, "【产品管理】更新产品状态异常: " + id + ", 状态: " + status + ", 错误: " + LogUtils.formatException(e));
            LogUtils.logBusiness(logger, "PRODUCT_STATUS_UPDATE_EXCEPTION", "system", "更新产品状态异常: " + e.getMessage());
            throw e;
        }
    }
    
    // 辅助方法：比较两个对象是否相等，处理null情况
    private boolean equals(Object a, Object b) {
        if (a == null && b == null) return true;
        if (a == null || b == null) return false;
        return a.equals(b);
    }
}